<template>
	<view class="content">
		<!-- <view style="font-size: 25px;">
			记录此刻，所思所想
		</view> -->
		<view>
			<u-grid :col="3" :showBorder="false">
				<u-grid-item bg-color="#f1f1f1;">
					<view class="grid-item-box">
						<u-avatar :src="avatar1" size="large" mode="square" @click="pageToPulishDaily()"></u-avatar>
					</view>
				</u-grid-item>
				<u-grid-item bg-color="#f1f1f1;">
					<view class="grid-item-box">
						<u-avatar :src="avatar2" size="large" mode="square" @click="openEatingShow()"></u-avatar>
					</view>
				</u-grid-item>
				<u-grid-item bg-color="#f1f1f1;">
					<view class="grid-item-box">
						<u-avatar :src="avatar3" size="large" mode="square" @click="openBillShow()"></u-avatar>
					</view>
				</u-grid-item>
				<u-grid-item bg-color="#f1f1f1;">
					<view class="grid-item-box">
						<u-avatar :src="avatar4" size="large" mode="square" @click="openWhispersShow()"></u-avatar>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
		<u-calendar v-model="showDate" mode="range" @change="change"></u-calendar>
		<u-action-sheet :list="actionList" v-model="showActionSheet" :cancel-btn="false"
			@click="settingOfOption"></u-action-sheet>
		<u-mask :show="show" @click="show = false">
			<view class="warp">
				<view class="rect" @tap.stop>
					<view style="font-size: 24px;display: flex;justify-content: center;">{{stepTitle}}</view>
					<view style="height: 80%;display: flex;justify-content: center;align-items: center;">
						<view v-if="stepOne">
							<u-input v-model="bigTarget" type="select" :border="false" @click="showSelect = true" />
							<u-action-sheet :list="actionSheetList" v-model="showSelect" :cancel-btn="false"
								@click="actionSheetCallback"></u-action-sheet>
							<view style="display: flex;justify-content: center;margin-top: 10%;">
								<u-button type="warning" size="mini" @click="show = false"
									style="margin-right: 5%;">关闭</u-button>
								<u-button type="success" size="mini" @click="next(1)">下一步</u-button>
							</view>
						</view>
						<view v-if="stepTwo">
							<input v-model="form.planTitle" type="text" placeholder-style="color:#bdbdbd"
								placeholder="请输入内容" confirm-type="next" @confirm="next(2)" />
						</view>
						<view v-if="stepThree">
							<view v-if="bigTarget !== '待办事项'">
								<view style="width: 100%;display: flex;justify-content: center;margin-bottom: 3%">
									开始日期：{{form.startTime == undefined?'':form.startTime}} </view>
								<u-divider></u-divider>
								<view style="width: 100%;display: flex;justify-content: center;margin-top: 3%">
									完成日期：{{form.endTime == undefined?'':form.endTime}} </view>
							</view>
							<view v-else>
								<u-divider>执行人</u-divider>
								<view style="display: flex;justify-content: center;margin: 3% 0;">
									<u-avatar v-for="(item,itemIndex) in selectedUserList" :key="itemIndex" size="50"
										:src="item.avatar"></u-avatar>
								</view>
							</view>
							<view style="display: flex;margin-top: 10%;justify-content: center;">
								<u-button type="warning" size="mini" style="margin-right: 5%;" @click="showDate = true"
									v-if="bigTarget !== '待办事项'">修改日期</u-button>
								<u-button type="warning" size="mini" style="margin-right: 5%;"
									@click="userListShow = true" v-if="bigTarget === '待办事项'">指定执行人</u-button>
								<u-button type="success" size="mini" @click="next(3)">下一步</u-button>
							</view>
						</view>
						<view v-if="stepFour">
							<view style="width: 100%;display: flex;justify-content: center;">
								<u-button type="primary" size="medium" style="margin-bottom: 5%;"
									@click="next(5)">继续添加</u-button>
							</view>
							<view style="width: 100%;display: flex;justify-content: center;">
								<u-button type="success" size="medium" @click="next(4)">完成计划</u-button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-mask>
		<u-mask :show="whispersShow" @click="whispersShow = false">
			<view class="warp">
				<view class="moneyRect" @tap.stop>
					<view class="title">规划你的钱袋子</view>
					<view class="moneyContent">
						<u-form-item label="钱袋子:" label-width="150">
							<u-input v-model="moneyTitle" type="text" :border="false" confirm-type="next"
								placeholder="叫什么名字呢？" />
						</u-form-item>
						<u-form-item label="额度:" label-width="150">
							<u-input v-model="moneyTotal" type="number" :border="false" confirm-type="next"
								placeholder="给多少额度呢？" />
						</u-form-item>
						<view class="button-group">
							<u-button type="success" size="medium" @click="moneyNext(1)">完成</u-button>
						</view>
					</view>
				</view>
			</view>
		</u-mask>
		<u-popup v-model="userListShow" mode="left" width="30%">
			<view style="margin-top: 50%;">
				<u-divider>可选执行人</u-divider>
			</view>
			<view class="item u-border-bottom" style="display: flex;flex-wrap: wrap;">
				<view v-for="(user,index) in userList" :key="index"
					:style="{'margin': '3%','background-color':user.selected?'#19be6b':'','border-radius':'50%'}">
					<u-avatar size="default" :src="user.avatar" @click="toggleSelected(user)"></u-avatar>
				</view>
			</view>
		</u-popup>
		<!-- <u-tabbar :list="tabbar" :mid-button="true"></u-tabbar> -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth'
	import {
		addEating
	} from '@/api/bot/eating'
	import {
		addMoney
	} from '@/api/bot/money'
	import {
		getListOfNoPage
	} from '@/api/system/user'
	import {
		getOneOfUser
	} from '@/api/bot/groupInvite'
	export default {
		data() {
			return {
				baseUrl: config.baseUrl,
				tabbar: [],
				groupId: '',
				uploadURL: config.baseUrl + '/common/upload',
				header: '',
				barTop: 0,
				avatar1: "/static/images/icon/icon1.png",
				avatar2: "/static/images/icon/icon2.png",
				avatar3: "/static/images/icon/icon3.png",
				avatar4: "/static/images/icon/money.png",
				showDate: false,
				dateRange: [],
				form: {},
				formData: [],
				show: false,
				whispersShow: false,
				bigTarget: '',
				stepOne: false,
				moneyTitle: '',
				moneyTotal: '',
				stepTwo: false,
				stepThree: false,
				stepFour: false,
				stepTitle: "选择清单类型",
				actionSheetList: [{
						text: '待办事项'
					}, {
						text: '出行计划'
					},
					{
						text: '存钱计划'
					},

					{
						text: '日常计划'
					},
					{
						text: '学习计划'
					}
				],
				showSelect: false,
				actionList: [{
					text: '拍照上传',
					subText: '单张图片上传'
				}, {
					text: '选择上传',
					subText: '多张图片上传'
				}],
				showActionSheet: false,
				fileInfo: null,
				userListShow: false,
				userList: [],
				selectedUserList: [],
			}
		},
		watch: {
			show(newValue) {
				if (!newValue) {
					this.form = {};
					this.bigTarget = ''
					this.selectedUserList = []
					this.stepOne = false
					this.stepTwo = false
					this.stepThree = false
					this.stepFour = false
					this.stepTitle = "选择清单类型"
				}
			}
		},
		onLoad: function() {
			this.tabbar = this.$store.state.tabbar;
		},
		onShow() {
			uni.getStorage({
				key: 'groupIdByIndex',
				success: (res) => {
					let data = JSON.parse(res.data);
					this.groupId = data.id;
					this.getListOfNoPage()
				}
			});
		},
		created() {
			// 1.获取屏幕可使用宽度
			let windowWidth = uni.getSystemInfoSync().windowWidth;
			// 2.获取状态栏高度
			const statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			// 3.获取胶囊按钮位置信息
			const menuButton = uni.getMenuButtonBoundingClientRect();
			// 4.计算出导航栏高度  换算成rpx
			let navHeight = (menuButton.height + (menuButton.top - statusBarHeight) * 2) * (750 / windowWidth);
			// 5.导航栏与状态栏拉开距离  margin-top: statusBarTop + 'rpx'; 
			const statusBarTop = statusBarHeight * (750 / windowWidth);
			this.barTop = statusBarTop;
			this.header = this.header || {}
			if (getToken()) {
				this.header['Authorization'] = 'Bearer ' + getToken()
			}
		},
		methods: {
			getListOfNoPage() {
				let query = {
					includeOfOwn: true,
					groupId: this.groupId
				}
				this.userList = []
				getOneOfUser(query).then(res => {
					res.rows.forEach(user => {
						const avatar = (user == null || user.avatar == "" || user.avatar == null) ?
							require("@/static/images/profile.jpg") : (user.avatar.includes("http") ?
								user.avatar : this.baseUrl + user.avatar);
						user.avatar = avatar
					})
					this.userList = res.rows
				})
			},
			toggleSelected(user) {
				this.$set(user, "selected", !user.selected);
				if (user.selected) {
					this.selectedUserList.push(user);
				} else {
					const index = this.selectedUserList.findIndex(selectedUser => selectedUser.userId === user.userId);
					console.log(index);
					if (index !== -1) {
						this.selectedUserList.splice(index, 1);
					}
				}
				console.log(this.selectedUserList.map(item => item.userId));
			},
			cancel() {
				this.userListShow = false
			},
			update() {
				let ids = this.selectedUserList.map(item => item.userId)
				// this.currentMoneyData.userIds = ids
				// console.log(ids);
				// updateMoney(this.currentMoneyData).then(res => {
				// 	if (res.code !== 200) {
				// 		this.$modal.msgError("保存失败")
				// 	} else {
				// 		this.getMoneyList()
				// 		this.userListShow = false
				// 		this.$modal.msgSuccess("保存成功")
				// 	}
				// })
			},
			moneyCancel() {
				this.whispersShow = false
				this.moneyTitle = '';
				this.moneyTotal = '';
				this.balanceTotal = '';
			},
			settingOfOption(index) {
				console.log(`点击了第${index + 1}项，内容为：${this.actionList[index].text}`)
				if (index == 0) {
					this.pulishEatingSingle()
				} else {
					this.pageToPulishEatting()
				}
			},
			async pulishEatingSingle() {
				const fileInfo = await this.uploadFile()
				const json = JSON.parse(fileInfo);
				let sysFileInfos = []
				let file = {
					fileName: json.newFileName,
					fileLocation: json.fileName,
					fileUrl: json.url
				}
				sysFileInfos.push(file);
				let formData = {
					sysFileInfos: sysFileInfos,
					groupId: this.groupId
				}
				addEating(formData).then(res => {
					if (res.code == 200) {
						this.$store.commit('SET_PUBLISHCONTENTTYPE', 1)
						this.$store.commit('IS_REFRESH', true)
						this.$tab.switchTab('/pages/index')
						this.$modal.msgSuccess("发布成功")
					} else {
						this.$modal.msgError("发布失败")
					}
				})
			},
			uploadFile() {
				return new Promise((resolve, reject) => {
					// 在某个事件触发时调用相机
					let uploadURL = this.uploadURL;
					let header = this.header;
					uni.chooseImage({
						count: 1, // 最多可选择的图片数量
						sourceType: ['camera'], // 指定来源为相机
						success: function(res) {
							const tempFilePaths = res.tempFilePaths; // 获取选择的图片临时文件路径
							// 将图片上传到接口
							console.log(uploadURL)
							uni.uploadFile({
								url: uploadURL, // 接口地址
								filePath: tempFilePaths[0], // 选择的图片路径
								name: 'file',
								header: header, // 后端接口接收的文件字段名
								success: function(response) {
									// 上传成功后的处理逻辑
									resolve(response.data) // 接口返回的数据
								},
								fail: function(error) {
									// 上传失败后的处理逻辑
									console.log(error);
									reject()
								}
							});
						},
						fail: function(error) {
							// 调用相机失败的处理逻辑
							console.log(error);
							reject()
						}
					});
				})
			},
			openBillShow() {
				this.formData = []
				this.show = true
				this.stepOne = true
				this.showSelect = true
			},
			openWhispersShow() {
				this.whispersShow = true
			},
			openEatingShow() {
				this.showActionSheet = true
			},
			// 点击actionSheet回调
			actionSheetCallback(index) {
				this.bigTarget = this.actionSheetList[index].text;
			},
			pageToPulishDaily() {
				this.$tab.navigateTo('/pages/publish/publishDaily')
			},
			pageToPulishEatting() {
				this.$tab.navigateTo('/pages/publish/publishEating')
			},
			pageToPulishBill() {
				let formData = {
					title: this.bigTarget,
					botBillCells: this.formData
				}
				const formDataStr = JSON.stringify(formData);
				this.$tab.navigateTo('/pages/publish/publishBill?formData=' + encodeURIComponent(formDataStr))
			},
			moneyNext(step) {
				if (step == 1) {
					this.whispersShow = false
					let formData = {
						moneyTitle: this.moneyTitle,
						moneyTotal: this.moneyTotal,
						balanceTotal: this.moneyTotal,
						groupId: this.groupId
					}
					uni.showLoading({
						title: "正在发布"
					})
					addMoney(formData).then(res => {
						if (res.code == 200) {
							this.$store.commit('SET_PUBLISHCONTENTTYPE', 2)
							this.$store.commit('IS_REFRESH', false)
							this.$tab.switchTab('/pages/index')
							this.$modal.msgSuccess("发布成功")
						} else {
							this.$modal.msgError("发布失败")
						}
						uni.hideLoading()
					})
				}
			},
			next(step) {
				if (step == 1) {
					this.stepOne = false
					this.stepTwo = true
					this.stepThree = false
					this.stepFour = false
					this.stepTitle = "输入清单项名称"
				} else if (step == 2 && this.bigTarget !== '待办事项') {
					this.stepOne = false
					this.stepTwo = false
					this.stepThree = true
					this.showDate = true
					this.stepTitle = "该清单项何时完成"
				} else if (step == 2 && this.bigTarget === '待办事项') {
					this.stepOne = false
					this.stepTwo = false
					this.stepThree = true
					this.userListShow = true
					this.stepTitle = "指定清单项执行人"
				} else if (step == 3 && this.bigTarget !== '待办事项') {
					if (this.form.startTime && this.form.endTime) {
						this.stepOne = false
						this.stepTwo = false
						this.stepThree = false
						this.stepFour = true
						this.stepTitle = "还有其他清单项吗"
					} else {
						this.$refs.uToast.show({
							title: `请填写计划时间`,
							type: 'warning',
						});
					}
				} else if (step == 3 && this.bigTarget === '待办事项') {
					this.stepOne = false
					this.stepTwo = false
					this.stepThree = false
					this.stepFour = true
					this.stepTitle = "还有其他清单项吗"
				} else if (step == 4) {
					this.stepOne = false
					this.stepTwo = false
					this.stepThree = false
					this.stepFour = false
					this.show = false
					this.form.selectedUserList = this.selectedUserList
					this.formData.push(this.form)
					this.pageToPulishBill()
				} else {
					this.form.selectedUserList = this.selectedUserList
					this.formData.push(this.form)
					this.form = {}
					this.selectedUserList = []
					this.next(1)
				}
			},
			change(e) {
				this.form.startTime = e.startDate
				this.form.endTime = e.endDate
			}
		}
	}
</script>

<style scoped lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 5rpx 15rpx;
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		width: 500rpx;
		height: 350rpx;
		background-color: #fff;
		border-radius: 30px;
		padding: 25rpx;
	}

	.moneyRect {
		width: 300px;
		background-color: #fff;
		border-radius: 8px;
		padding: 20px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	.title {
		font-size: 18px;
		display: flex;
		justify-content: center;
		margin-bottom: 20px;
	}

	.moneyContent {
		height: 80%;
		display: flex;
		flex-direction: column;
		padding: 5rpx 15rpx;
	}

	.button-group {
		width: 100%;
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
</style>